#!/usr/bin/python
# -*- coding: utf-8 -*-
#coding=utf-8

import os
import base64
import urllib.parse
import hashlib
from Crypto.Cipher import AES
import datetimeDemo as tsLog
import fileDemo

#from binascii import b2a_hex, a2b_hex
def makeBase64Bytes(strOrBytes):
    if isinstance(strOrBytes, str):
        strBytes = strOrBytes.encode('utf-8')
        b64Bytes = base64.b64encode(strBytes)
        return b64Bytes
    elif isinstance(strOrBytes, bytes):
        b64Bytes = base64.b64encode(strOrBytes)
        return b64Bytes
    else:
        return None
def makeBase64Str(strOrBytes):
    b64Bytes = makeBase64Bytes(strOrBytes)
    if b64Bytes:
        b64Str = b64Bytes.decode('utf-8')
        return b64Str
    else:
        return None

def decodeBase642Bytes(strOrBytes):
    if isinstance(strOrBytes, str):
        strBytes = strOrBytes.encode('utf-8')
        decodeBytes = base64.b64decode(strBytes)
        return decodeBytes
    elif isinstance(strOrBytes, bytes):
        decodeBytes = base64.b64decode(strOrBytes)
        return decodeBytes
    else:
        return None

def decodeBase642Str(strOrBytes):
    dBytes = decodeBase642Bytes(strOrBytes)
    if dBytes:
        dStr = dBytes.decode('utf-8')
        return dStr
    else:
        return None
def makeUrlEncode(urlStr):
    if isinstance(urlStr, str):
        return urllib.parse.quote(urlStr)
    elif isinstance(urlStr, bytes):
        return urllib.parse.quote(urlStr.decode('utf-8'))
    else:
        return None

def makeUrlDecode(urlEncodeStr):
    if isinstance(urlEncodeStr, str):
        return urllib.parse.unquote(urlEncodeStr, 'utf-8')
    elif isinstance(urlEncodeStr, bytes):
        return urllib.parse.unquote(urlEncodeStr.decode('utf-8'), 'utf-8')
    else:
        return None

def makeMd5HexStr(strOrBytes):
    if isinstance(strOrBytes, str):
        strBytes = strOrBytes.encode('utf-8')
        md5Gen = hashlib.md5()
        md5Gen.update(strBytes)
        return md5Gen.hexdigest()
    elif isinstance(strOrBytes, bytes):
        md5Gen = hashlib.md5()
        md5Gen.update(strOrBytes)
        return md5Gen.hexdigest()
    else:
        return None
def makeFileMd5HexStr(filePath):
    with open(filePath, 'rb') as fr:
        content = fr.read()
        md5Gen = hashlib.md5()
        md5Gen.update(content)
        fr.close()
        return md5Gen.hexdigest()

    return None

def makeHexStr(strOrBytes):
    if isinstance(strOrBytes, str):
        strBytes = strOrBytes.encode('utf-8')
        return strBytes.hex()
    elif isinstance(strOrBytes, bytes):
        return strOrBytes.hex()
    else:
        return None

#补0对齐16位
def addTo16Bytes(oStr):
    sBytes = oStr.encode('utf-8')
    while len(sBytes) % 16 != 0:
        sBytes += b'\x00'
    return sBytes
def makeAESEncrypt(oStr, key):
    # 将oStr做AES加密
    #key = '1234567890123456'
    # https://blog.csdn.net/wzxiaodu/article/details/121905131

    mode = AES.MODE_ECB
    #iv = b'qqqqqqqqqqqqqqqq'
    cryptor = AES.new(addTo16Bytes(key), mode)

    encryptBytes = cryptor.encrypt(addTo16Bytes(oStr))
    encryptBase64Bytes = base64.encodebytes(encryptBytes)
    encryptBase64Str = encryptBase64Bytes.decode('utf-8')
    return encryptBase64Str

def makeAESDecrypt(encryptStr, key):
    mode = AES.MODE_ECB
    #iv = b'qqqqqqqqqqqqqqqq'
    cryptor = AES.new(addTo16Bytes(key), mode)

    b64StrBytes = encryptStr.encode('utf-8')
    encryptBytes = base64.b64decode(b64StrBytes)

    decryptBytes = cryptor.decrypt(encryptBytes)

    try:
        decryptStr = decryptBytes.decode('utf-8')
    except Exception as err:
        decryptStr = ''

    #加密的时候补的0在这里去除
    decryptStr = decryptStr.rstrip('\0')

    return decryptStr

def base64Demo():
    print("\nbase64Demo")
    oStr = """
七律·长征
毛泽东
1935年10月
红军不怕远征难，万水千山只等闲
五岭逶迤腾细浪，乌蒙磅礴走泥丸。
金沙水拍云崖暖，大渡桥横铁索寒。
更喜岷山千里雪，三军过后尽开颜。
    """
    print("oStr", len(oStr), oStr)

    b64Str = makeBase64Str(oStr)
    print("b64Str", len(b64Str), b64Str)

    decodeStr = decodeBase642Str(b64Str)
    print("decodeStr", len(decodeStr))
    print("decodeStr == oStr", decodeStr == oStr)


def urlCodeDemo():
    print("\nurlCodeDemo")

    oStr = "https://www.baidu.com/s?tn=50000021_hao_pg&ie=utf-8&word=swift如何做urlencode site:jianshu.com"
    print("oStr", len(oStr), oStr)

    urlEncode = makeUrlEncode(oStr)
    print("urlEncode", len(urlEncode), urlEncode)

    urlDecode = makeUrlDecode(urlEncode)
    print("urlDecode", len(urlDecode), urlDecode)

def md5Demo():
    print("\nmd5Demo")
    oStr = """
七律·长征
毛泽东
1935年10月
红军不怕远征难，万水千山只等闲
五岭逶迤腾细浪，乌蒙磅礴走泥丸。
金沙水拍云崖暖，大渡桥横铁索寒。
更喜岷山千里雪，三军过后尽开颜。
"""
    print("oStr", len(oStr))

    # 提取字符串 a 的md5摘要
    md5Str = makeMd5HexStr(oStr)
    print("md5Str", len(md5Str), md5Str)

    # 本地文件 计算它 的 md5摘要
    currentDirectory = fileDemo.check2CreateWorkDir()
    poemFilePath = os.path.join(currentDirectory, "poem.txt")

    fileMd5Str = makeFileMd5HexStr(poemFilePath)
    print("fileMd5Str", len(fileMd5Str), fileMd5Str, poemFilePath)

def AESDemo():
    print("\nAESDemo")
    oStr = """
七律·长征
毛泽东
1935年10月
红军不怕远征难，万水千山只等闲
五岭逶迤腾细浪，乌蒙磅礴走泥丸。
金沙水拍云崖暖，大渡桥横铁索寒。
更喜岷山千里雪，三军过后尽开颜。
"""
    print("oStr", len(oStr))
    aesCrypt = makeAESEncrypt(oStr, 'asdfghjkl')
    print("aesCrypt", len(aesCrypt), aesCrypt)

    decrypt = makeAESDecrypt(aesCrypt, '__asdfghjkl')
    print("decrypt, wrong key", len(decrypt), decrypt)
    print("wrong key, decrypt == oStr", decrypt == oStr)

    decrypt = makeAESDecrypt(aesCrypt, 'asdfghjkl')
    print("decrypt, right key", len(decrypt), decrypt)
    print("right key, decrypt == oStr", decrypt == oStr)

def demo():
    tsLog.logTs("encryptDemo", preNewLineNum=2)

    md5Demo()
    
    base64Demo()

    urlCodeDemo()

    AESDemo()


if __name__ == '__main__':
    demo()